# frozen_string_literal: true

module Security
  module Ingestion
    module Tasks
      # Ingests the data for the `Vulnerabilities`::Flag` model.
      class IngestVulnerabilityFlags < AbstractTask
        include Gitlab::Ingestion::BulkInsertableTask

        MAX_DESCRIPTION_LENGTH = 1_000

        self.model = Vulnerabilities::Flag
        self.unique_by = %i[vulnerability_occurrence_id flag_type origin].freeze
        self.uses = :id

        private

        def attributes
          finding_maps.flat_map { |finding_map| flag_attributes_for(finding_map) }
        end

        def after_ingest
          model.where(finding: finding_ids).where.not(id: return_data).delete_all # rubocop:disable CodeReuse/ActiveRecord
        end

        def finding_ids
          finding_maps.map(&:finding_id)
        end

        def flag_attributes_for(finding_map)
          finding_map.report_finding.flags.map do |vulnerability_flag|
            vulnerability_flag.to_h.merge!(vulnerability_occurrence_id: finding_map.finding_id,
                                           description: description_for(vulnerability_flag))
          end
        end

        def description_for(vulnerability_flag)
          vulnerability_flag.description&.truncate(MAX_DESCRIPTION_LENGTH)
        end
      end
    end
  end
end
